package com.example.CarManagement.config.SecurityConfig;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import cn.hutool.core.util.StrUtil;
import com.example.CarManagement.exception.ServiceException;
import com.example.CarManagement.sys.entity.LoginUser;
import com.example.CarManagement.sys.entity.Permission;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * 自定义权限实现，se取自SpringSecurity
 *
 * @author 徐佳彪
 */
@Service("se")
public class PermissionService {
    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPermi(String permission) {
        if (StrUtil.isEmpty(permission)) {
            return false;
        }

        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            LoginUser loginUser = (LoginUser) authentication.getPrincipal();


            if (loginUser == null || CollectionUtils.isEmpty(loginUser.getPermissions())) {
                return false;
            }


            PermissionContextHolder.setContext(permission);

            // 将权限字符添加到set集合
            List<Permission> permissions = loginUser.getPermissions();

            Set<String> permissionSet = permissions.stream().map(Permission::getName).collect(Collectors.toSet());

            return permissionSet.contains(StrUtil.trim(permission));
        } catch (Exception e) {
            throw new ServiceException("获取用户信息异常");
        }

    }


}
